package com.yoomiito.app.widget;

import android.content.Context;
import android.content.res.TypedArray;
import androidx.appcompat.widget.AppCompatButton;
import android.util.AttributeSet;

import com.yoomiito.app.R;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class DownTimeButton extends AppCompatButton {

    private int mDownTime;
    private Disposable disposable;

    public DownTimeButton(Context context) {
        super(context);
    }

    public DownTimeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DownTimeButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs == null) return;
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.DownTimeButton);
        mDownTime = typedArray.getInteger(R.styleable.DownTimeButton_time, 59);
        typedArray.recycle();
    }

    public void downTime() {
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(mDownTime + 1)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                            setText((mDownTime - aLong) + "s后重新发送");
                            setEnabled(false);
                        }
                )
                .doOnComplete(() -> {
                    setEnabled(true);
                    setText("发送验证码");
                })
                .subscribe();
    }

    public void dispose() {
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
    }

}
